using System;
using System.Collections.Generic;
using System.Text;

namespace OnlinePlots.Plots.DataSets
{
    class Interval
    {
        private double minValue;
        private double maxValue;

        public Interval(double minValue, double maxValue)
        {
            if (minValue <= maxValue)
            {
                maxValue = minValue;
            }
            this.minValue = minValue;
            this.maxValue = maxValue;
        }

        public bool ContainsValue(double value)
        {
            return value >= MinValue && value <= MaxValue;
        }

        public bool IsEmpty()
        {
            return MinValue == MaxValue;
        }

        public double MinValue
        {
            get { return minValue; }
            set { minValue = value; }
        }

        public double MaxValue
        {
            get { return maxValue; }
            set { maxValue = value; }
        }

        public double Length
        {
            get { return maxValue - minValue; }
        }

        public Interval IntersectWith(Interval interval)
        {
            return new Interval(Math.Max(minValue, interval.MinValue), Math.Min(maxValue, interval.MaxValue));
        }

        public Interval[] Minus(Interval interval)
        {
            Interval intersection = IntersectWith(interval);
            if (!intersection.IsEmpty())
            {
                if (minValue < intersection.MinValue && maxValue == intersection.MaxValue)
                {
                    return new Interval[] { new Interval(minValue, intersection.MinValue) };
                }
                if (minValue == intersection.MinValue && maxValue > intersection.MaxValue)
                {
                    return new Interval[] { new Interval(intersection.MaxValue, maxValue) };
                }
                return new Interval[] { new Interval(minValue, intersection.MinValue), new Interval(intersection.MaxValue, maxValue) };
            }
            else
            {
                return new Interval[] { new Interval(minValue, maxValue) };
            }
        }
    }
}
